<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: mapi_app.php 3786 2014-01-22 06:52:44Z laoguozhang $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

/**
 * Description of web_app
 *
 * @author bilicen
 */

class stat_app extends dzf_base_application {

	public $appname = 'stat';


	public $init_db = 0;
	public $mobile = array();
	public $member;
	public $var;
	public $config;
	public $siteurl = '';
	public $setting = array();
	// 是否已经初始化
	public $initated = false;
	
	//公共签名密钥
	protected $signkey = 'a029ae241ef07293bea0286c8d32ddfa';
	
	//私人签名密钥
	public $authkey = '';
	
	//是否查检版本更新
	public $ischeckupdate = false;

	// 列举全局变量，为清理做准备
	public $superglobal = array(
		'GLOBALS' => 1,
		'_GET' => 1,
		'_POST' => 1,
		'_REQUEST' => 1,
		'_COOKIE' => 1,
		'_SERVER' => 1,
		'_ENV' => 1,
		'_FILES' => 1,
	);
	
	//手机app全局回传参数
	public $sys = array();
	
	public $attachurl = 'http://ugc.qpic.cn/dczmobile/10000/';
	public $threadcoverurl = 'http://ugc.qpic.cn/dzmobilepic/10000/c';
	public $originalimgurl = 'http://ugc.qpic.cn/dzmobilepic/10000/'; //保存原图地址:无质量下降的图片
	public $threadcoverminiurl = 'http://ugc.qpic.cn/dczmobile/40000/c';
	public $grouplogourl = 'http://ugc.qpic.cn/dczmobile/20000/';
	public $splashurl = 'http://ugc.qpic.cn/dczmobile/30000/s';
	public $threadcover12url = 'http://ugc.qpic.cn/discuz_mobile/10000/c';
	public $defaultavatarurl = 'http://ugc.qpic.cn/dczmobile/20000/g426_1375778776/0'; //默认头像

	public $retieurl = 'http://retie.qq.com/';
	
	public $firstsign = false;
	
	public $isnotification = false;

	//note 
	public $iconurl = array(
		'threadtopic' => array(
			'1' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.99ee7f5d1d60134a4e1cac27d5eacec7/0',
			'2' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.99ee7f5d1d60134a4e1cac27d5eacec7/0',
			'3' => 'http://ugc.qpic.cn/dczmobile/10000/50.24.01d5ef756f58a11e1852416949fb0faa/0',
			'11' => 'http://ugc.qpic.cn/dczmobile/10000/67.32.f2343dd74583fe22a7e9d7c1928e0d10/0',
			'12' => 'http://ugc.qpic.cn/dczmobile/10000/33.16.41aa9f7d02eb7652f5b5ca53bde64351/0',
		),
		'gif' => array(
			'1' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.b0d2687a647523ac98144cd2a85cf7eb/0',
			'2' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.b0d2687a647523ac98144cd2a85cf7eb/0',
			'3' => 'http://ugc.qpic.cn/dczmobile/10000/50.24.ae40711f16f3c7d3dffafee91516dee6/0',
			'11' => 'http://ugc.qpic.cn/dczmobile/10000/67.32.35329307f57e4ad46c5d47a9876f30c4/0',
			'12' => 'http://ugc.qpic.cn/dczmobile/10000/33.16.d99c053cc232d9f01d85726ccd9164ae/0',
		),
		'video' => array(
			'1' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.74825ad3697ebf2d9dcbb8b1e35ee2f1/0',
			'2' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.74825ad3697ebf2d9dcbb8b1e35ee2f1/0',
			'3' => 'http://ugc.qpic.cn/dczmobile/10000/50.24.4a118ffbd2aa41caa011bdfe1ec798b0/0',
			'11' => 'http://ugc.qpic.cn/dczmobile/10000/67.32.d994f62be930e50f205faa006b8a9bd0/0',
			'12' => 'http://ugc.qpic.cn/dczmobile/10000/33.16.93cf0e819676b7e5a42bd18ae0094d5b/0',
		),
		'topicring' => array(
			'1' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.e6e32732fe62ff84a744f0b4b3bcba58/0',
			'2' => 'http://ugc.qpic.cn/dczmobile/10000/76.36.e6e32732fe62ff84a744f0b4b3bcba58/0',
			'3' => 'http://ugc.qpic.cn/dczmobile/10000/50.24.09b63290c2cc1e3bdc809f6afaa28bb3/0',
			'11' => 'http://ugc.qpic.cn/dczmobile/10000/67.32.c95401d4b4e379e5490ef88efb1e814e/0',
			'12' => 'http://ugc.qpic.cn/dczmobile/10000/33.16.f2030d75b6c390725fae6b55daef01e3/0',
		),
	);
	
	/**
	 * 手机类型
	 * @var array 
	 */
	public $mobiletype =  array(
			'ios' => 1,
			'and' => 2,
			'wp' => 3,
		);
	
	public $mobilepixels = array(
		'1' => array('w' => 1920, 'h' => 1080),
		'2' => array('w' => 1280, 'h' => 720),
		'3' => array('w' => 800, 'h' => 480),
		'11' => array('w' => 960, 'h' => 640),
		'12' => array('w' => 480, 'h' => 320),
	);
	
	/**
	 * resolution	位置	手机分辨率	缩略方式（单位为px）
		1	Android 内容页正文图片	1920X1080	990*不限高
		2	Android 内容页正文图片	1280X720	660*不限高
		3	Android 内容页正文图片	800X480	440*不限高
		11	iOS 内容页正文图片	960X640	586*不限高
		12	iOS 内容页正文图片	480X320	292*不限高
		Android 主题列表题图	1920X1080	310*225（按照最小边等比缩放，然后裁剪。以下相同方式）
		Android 主题列表题图	1280X720	207*150
		Android 主题列表题图	800X480	138*100
		iOS 主题列表题图	960X640	184*133
		iOS 主题列表题图	480X320	92*67
	 * @var array
	 */
	public $thumbpixels = array(
		'view' => array(
		    '1' => array('w' => '990', 'h' => ''),//? = round(w/h*990)
		    '2' => array('w' => '660', 'h' => ''),
		    '3' => array('w' => '440', 'h' => ''),
		    '11' => array('w' => '586', 'h' => ''),
		    '12' => array('w' => '586', 'h' => ''),//'12' => array('w' => '292', 'h' => ''),
		    ),
		'list' => array(
		    '1' => array('w' => '310', 'h' => '255'),
		    '2' => array('w' => '207', 'h' => '150'),
		    '3' => array('w' => '138', 'h' => '100'),
		    // '11' => array('w' => '184', 'h' => '133'), //IOS未发布使用
		    //'12' => array('w' => '92', 'h' => '67'),//IOS未发布使用
		),
		'listtop' => array(
		    '1' => array('w' => '990', 'h' => '585'),
		    '1' => array('w' => '660', 'h' => '390'),//1920*1080暂时返回660尺寸
		    '2' => array('w' => '660', 'h' => '390'),
		    '3' => array('w' => '440', 'h' => '260'),
		    //'11' => array('w' => '586', 'h' => '346'),//IOS未发布使用
		    //'12' => array('w' => '292', 'h' => '173'),//IOS未发布使用
		),
		
		//版本1.2
		'list2' => array(
		    '1' => array('w' => '141', 'h' => '126'),// 分辨率没有匹配到时的默认值
		    '2' => array('w' => '207', 'h' => '177'),// Android: 1280X720
		    '3' => array('w' => '141', 'h' => '126'),// Android: 800X480
		    '11' => array('w' => '182', 'h' => '148'),// iOS: 960X640
		    '12' => array('w' => '141', 'h' => '126'),// iOS: 480X320
		),
		//版本1.2
		'listtop2' => array(
		    '1' => array('w' => '480', 'h' => '288'),// 分辨率没有匹配到时的默认值
		    '2' => array('w' => '720', 'h' => '390'),// Android: 1280X720 //android 列表页面统一使用480图片，相比720图片可以减少原来的31%
		    //'2' => array('w' => '480', 'h' => '288'),// Android: 1280X720
		    '3' => array('w' => '480', 'h' => '288'),// Android: 800X480
		    '11' => array('w' => '640', 'h' => '312'),// iOS: 960X640
		    '12' => array('w' => '480', 'h' => '288'),// iOS: 480X320
		    //'11' => array('w' => '480', 'h' => '288'),// iOS: 960X640 //IOS列表页面统一使用480图片，大小可以减少原来的31%
		),

		'threadtopic' => array(
		    '1' => array('w' => '480', 'h' => '288'),// 分辨率没有匹配到时的默认值
		    '2' => array('w' => '720', 'h' => '390'),// Android: 1280X720 //android 列表页面统一使用480图片，相比720图片可以减少原来的31%
		    '3' => array('w' => '480', 'h' => '288'),// Android: 800X480
		    '11' => array('w' => '640', 'h' => '312'),// iOS: 960X640
		    '12' => array('w' => '480', 'h' => '288'),// iOS: 480X320
		),

		'orig' => array(
			'w' => '0',
			'h' => '0',
		),
	);
	
	/**
	 * 核心初始化
	 */
	public function init() {
		if(!$this->initated) {

			$this->_init_env();
			$this->_init_config();
			$this->_init_input();
			$this->_init_output();
			$this->_init_param();
			$this->_init_db();
		}
		$this->initated = true;
	}
	
	public function run() {
		/*
		$this->_init_setting();
		$this->_init_user();
		$this->_check_sign();
		$this->_from();
		 * 
		 */
		
		parent::run();
	}

	/**
	 * 
		uuid	客户端唯一id	string
		pf	平台(and/ios/wp)	string
		build	编译号	string
		version	版本	string
		apiVersion	接口版本，当前为1	string
		sig	签名	string
		ts	时间戳	int
		//skey	qq用户的skey	string(可选)
		uin	用户的qq	string(可选)
		token	ios的token，用于推送	string(可选)
		pixels	手机分辨率索引	int
	 */
	protected function _init_param() {
		$c = $this->request()->get_string('c');
		$a = $this->request()->get_string('a');
		$this->isnotification = $c === 'notification' && ($a === 'list' || $a === 'get');
		$this->ischeckupdate = !$this->isnotification && $c === 'update' && $a === 'check';
		$param = $this->request()->get_string('_param');
		if($param) {
			$param = str_replace(array('..', '/'), '', $param);
			//格式：$_GET['_param'] = mobileId|pf|build|version|apiVersion|ts|uin|token|pixels|skey|net
			@list($this->mobile['id'], $this->mobile['pf'], $this->mobile['build'], $this->mobile['version'], $this->mobile['apiVersion'], $this->mobile['ts'],  $this->mobile['uin'], $this->mobile['token'], $this->mobile['pixels'], $this->mobile['skey'], $this->mobile['net']) = explode('|', $param);
			//昵称独立传入：$_GET['nickName']
			$this->mobile['nickname'] = $this->request()->get_string('nickName');
			$this->mobile = array_map(trim, $this->mobile);
			$this->mobile['ext'] = $this->_parse_ext($this->request()->get_string('ext'));
		}
	}

	private function _parse_ext($ext) {
		return array('type' => substr($ext, 0, 2), 'id' => substr($ext, 2));
	}

	public function _from() {
		$from = $this->request()->get_string('from'); 
		if($from) {
			/*
				1  正常打开  1
				2  唤醒      2
				3  通知打开  3|[ext]
				4  分享打开  4|[sharetype]|[aid] 
			*/
			$fromarr = explode('|', $from);
			$fromtype = $fromarr[0];
			switch($fromtype) {
				case 1://note 启动
					$fromtype = 'common';
					$fromid = '';
					break;
				case 2://note 唤醒
					$fromtype = 'wakeup';
					$fromid = '';
					break;
				case 3://note 通知
					$ext = substr($from, strpos($from, '|')+1);
					$ext = $this->_parse_ext($ext);
					$noidarr = explode('|', $ext['id']);
					if(isset($noidarr[2])) {
						$fromtype = 'article';
						$fromid = $noidarr[2];
					} else {
						$fromtype = 'my';
						$fromid = '';
					}
					break;
				case 4://note 分享
					$fromtype = $fromarr[1];
					$fromid = $fromarr[2];
					break;
			}
			DZF::ext('dc')->update_check($fromtype, $fromid);
		}
	}

	/**
	 * 数据通信的签名检查
	 * @return boolean
	 */
	protected function _check_sign()
	{
		//测试使用
		//if($this->mobile['build'] === '1' || $this->request()->get_string('debug') === $this->request()->get_string('sig')) {
		if($this->mobile['build'] === 'dz' || $this->request()->get_string('c') === 'view' && $this->request()->get_string('a') === 'articleview') {
			return TRUE;
		}
		$data = $this->request()->get();
		//post数据添加签名
		$post = $this->request()->post();
		if(!empty($post) && is_array($post)) {
			$data = array_merge($data, $post);
		}
		unset($data['sig']);
		ksort($data);
		$source = implode('', $data);
		
		//修复最后活动时间
		if(!$this->member['lastactivity']) {
			DZF::m('member')->update_lastactivity($this->member['uid']);
			$this->member['lastactivity'] = TIMESTAMP;
		}
		
		$authkey = $this->makeprivatekey($this->member['lastactivity']);
		//检查版本更新时使用私人密钥
		if($this->ischeckupdate) {
			$this->authkey = $authkey;
			$authkey = '';
		}
		//var_dump($data, $this->member, $source, $this->signkey,md5(md5($source.$this->signkey.$authkey)), $this->request()->get_string('sig'));exit;
		$sig = md5(md5($source.$this->signkey.$authkey));
		/*if(function_exists('apc_store')) {
			apc_store('sig', array('source = '.$source.$this->signkey.$authkey, 'sig     = '.$sig, 'get[s]  = '.$this->request()->get_string('sig'), 'psignkey= '.$this->signkey, 'authkey = '.$authkey, md5('$')));
		}*/
		//var_dump('source = '.$source.$this->signkey.$authkey, 'sig     = '.$sig, 'get[s]  = '.$this->request()->get_string('sig'), 'psignkey= '.$this->signkey, 'authkey = '.$authkey);exit;
		if($sig === $this->request()->get_string('sig')) {
			return TRUE;
		} else {
			if($this->ischeckupdate) {
				$this->authkey = '';
			}
			$this->show_msg(stat_base_msg::SIGN_ERROR); //签名错误
		}
	}

	/**
	 * 获取个人通信加密密钥
	 * @param type $val
	 * @return type
	 */
	public function makeprivatekey($val) {
		if($this->authkey) {
			return $this->authkey;
		} else {
			//有效期为11天
			//$key = substr(md5(strrev(substr($val, 0, 4)).$this->signkey), 16);
			$key = (string)$this->member['uid'];
			//ios 调整签名机制，测试签名
			if($key === '622') {
				$key = (string)(round(TIMESTAMP / 10) * 10);
			}
			return $key;
		}
	}

	/**
	 * 定义PHP环境信息常量和全局变量 $_G
	 *
	*/
	private function _init_env() {

		error_reporting(E_ERROR);
		if(PHP_VERSION < '5.3.0') {
			set_magic_quotes_runtime(0);
		}

		define('MAGIC_QUOTES_GPC', function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc());
		define('ICONV_ENABLE', function_exists('iconv'));
		define('MB_ENABLE', function_exists('mb_convert_encoding'));
		define('EXT_OBGZIP', function_exists('ob_gzhandler'));

		define('TIMESTAMP', time());
		$this->timezone_set();

		/**
		 * 部分php环境内存设置过低，导致程序无法正常工作，此处判断当内存分配小于32M时，将内存加大至 128M
		 * 经测试，X系统如果php限制内存小于8M时程序将会运行异常
		 */
		if(function_exists('ini_get')) {
			$memorylimit = @ini_get('memory_limit');
			if($memorylimit && $this->return_bytes($memorylimit) < 33554432 && function_exists('ini_set')) {
				ini_set('memory_limit', '128m');
			}
		}

		//是否搜索引擎访问
		//define('IS_ROBOT', checkrobot());

		//清理全局变量
		foreach ($GLOBALS as $key => $value) {
			if (!isset($this->superglobal[$key])) {
				$GLOBALS[$key] = null; unset($GLOBALS[$key]);
			}
		}

	}

	/**
	 * Returns the relative URL of the entry script.
	 * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
	 * @return string the relative URL of the entry script.
	 */
	private function _get_script_url() {
		if(!isset($this->var['PHP_SELF'])){
			$scriptName = basename($_SERVER['SCRIPT_FILENAME']);
			if(basename($_SERVER['SCRIPT_NAME']) === $scriptName) {
				$this->var['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
			} else if(basename($_SERVER['PHP_SELF']) === $scriptName) {
				$this->var['PHP_SELF'] = $_SERVER['PHP_SELF'];
			} else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $scriptName) {
				$this->var['PHP_SELF'] = $_SERVER['ORIG_SCRIPT_NAME'];
			} else if(($pos = strpos($_SERVER['PHP_SELF'],'/'.$scriptName)) !== false) {
				$this->var['PHP_SELF'] = substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
			} else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT']) === 0) {
				$this->var['PHP_SELF'] = str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
				$this->var['PHP_SELF'][0] != '/' && $this->var['PHP_SELF'] = '/'.$this->var['PHP_SELF'];
			} else {
				$this->system_error('request_tainting');
			}
		}
		return $this->var['PHP_SELF'];
	}

	private function _init_input() {
		//note 禁止对全局变量注入
		if (isset($_GET['GLOBALS']) ||isset($_POST['GLOBALS']) ||  isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
			$this->system_error('request_tainting');
		}

		// slashes 处理
		if(MAGIC_QUOTES_GPC) {
			$_GET = $this->dstripslashes($_GET);
			$_POST = $this->dstripslashes($_POST);
			$_COOKIE = $this->dstripslashes($_COOKIE);
		}

//		//cookie 处理
//		$prelength = strlen($this->config['cookie']['cookiepre']);
//		foreach($_COOKIE as $key => $val) {
//			if(substr($key, 0, $prelength) == $this->config['cookie']['cookiepre']) {
//				$this->var['cookie'][substr($key, $prelength)] = $val;
//			}
//		}
//
//		$this->var['mod'] = empty($_GET['mod']) ? '' : $this->dhtmlspecialchars($_GET['mod']);
//		$this->var['inajax'] = empty($_GET['inajax']) ? 0 : (empty($this->var['config']['output']['ajaxvalidate']) ? 1 : ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || $_SERVER['REQUEST_METHOD'] == 'POST' ? 1 : 0));
//		$this->var['page'] = empty($_GET['page']) ? 1 : max(1, intval($_GET['page']));
//		$this->var['sid'] = $this->var['cookie']['sid'] = isset($this->var['cookie']['sid']) ? $this->dhtmlspecialchars($this->var['cookie']['sid']) : '';
//
//		//新的加密机制，与浏览器的类型无关
//		if(empty($this->var['cookie']['saltkey'])) {
//			$this->var['cookie']['saltkey'] = random(8);
//			$this->dsetcookie('saltkey', $this->var['cookie']['saltkey'], 86400 * 30, 1, 1);
//		}
//		$this->var['authkey'] = md5($this->var['config']['security']['authkey'].$this->var['cookie']['saltkey']);

	}

	protected function system_error($msg = '') {
		//todo log msg
		throw new Exception($msg);
		exit();
	}
	private function _init_config() {
		$_config = $this->config;
		if(empty($_config['security']['authkey'])) {
			$_config['security']['authkey'] = md5($_config['cookie']['cookiepre'].$_config['db'][1]['dbname']);
		}

		if(0 && (empty($_config['debug']) || !file_exists(libfile('function/debug')))) {
			define('DISCUZ_DEBUG', false);
			error_reporting(0);
		} elseif($_config['debug'] === 1 || $_config['debug'] === 2 || !empty($_REQUEST['debug']) && $_REQUEST['debug'] === $_config['debug']) {
			define('DISCUZ_DEBUG', true);
			error_reporting(E_ERROR);
			if($_config['debug'] === 2) {
				error_reporting(E_ALL);
			}
		} else {
			define('DISCUZ_DEBUG', false);
			error_reporting(0);
		}
		define('STATICURL', !empty($_config['output']['staticurl']) ? $_config['output']['staticurl'] : 'static/');
		$this->var['staticurl'] = STATICURL;

		$this->config = & $_config;
		$this->var['config'] = & $_config;

		if(substr($_config['cookie']['cookiepath'], 0, 1) != '/') {
			$this->var['config']['cookie']['cookiepath'] = '/'.$this->var['config']['cookie']['cookiepath'];
		}
		$this->var['config']['cookie']['cookiepre'] = $this->var['config']['cookie']['cookiepre'].substr(md5($this->var['config']['cookie']['cookiepath'].'|'.$this->var['config']['cookie']['cookiedomain']), 0, 4).'_';

		// 去掉加密key对浏览器的依赖
		// $this->var['authkey'] = md5($_config['security']['authkey'].$_SERVER['HTTP_USER_AGENT']);

	}

	private function _init_output() {

		//note security for url request
		if($this->config['security']['urlxssdefend'] && $_SERVER['REQUEST_METHOD'] == 'GET' && !empty($_SERVER['REQUEST_URI'])) {
			$this->_xss_check();
		}

		//防页面刷新
		if($this->config['security']['attackevasive'] && (!defined('CURSCRIPT') || !in_array($this->var['mod'], array('seccode', 'secqaa', 'swfupload')) && !defined('DISABLEDEFENSE'))) {
			require_once libfile('misc/security', 'include');
		}

		//客户端不支持 gzip
		if(!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) {
			$this->config['output']['gzip'] = false;
		}

		// 开启gzip判断
		$allowgzip = $this->config['output']['gzip'] && empty($this->var['inajax']) && $this->var['mod'] != 'attachment' && EXT_OBGZIP;
		$this->setglobal('gzipcompress', $allowgzip);

		ob_end_clean();
		// bug兼容 php 5.4.0 - 5.4.4
		if(!ob_start($allowgzip ? 'ob_gzhandler' : null)) {
			ob_start();
		}

		//note charset and header
		$this->setglobal('charset', $this->config['output']['charset']);
		define('CHARSET', $this->config['output']['charset']);
		if($this->config['output']['forceheader']) {
			@header('Content-Type: text/html; charset='.CHARSET);
		}

	}

	public function reject_robot() {
		if(IS_ROBOT) {
			exit(header("HTTP/1.1 403 Forbidden"));
		}
	}

	/**
	 * GET 参数跨站检测
	 *
	 * 2011-3-8 增加对 CONTENT-TRANSFER-ENCODING 代码的检测 (IE MHTML 漏洞)
	 * http://www.80vul.com/webzine_0x05/0x05%20IE%E4%B8%8BMHTML%E5%8D%8F%E8%AE%AE%E5%B8%A6%E6%9D%A5%E7%9A%84%E8%B7%A8%E5%9F%9F%E5%8D%B1%E5%AE%B3.html
	 */
	private function _xss_check() {
		$temp = strtoupper(urldecode(urldecode($_SERVER['REQUEST_URI'])));
		if(strpos($temp, '<') !== false || strpos($temp, '"') !== false || strpos($temp, 'CONTENT-TRANSFER-ENCODING') !== false) {
			$this->system_error('request_tainting');
		}
		return true;
	}

	private function _init_db() {
		if(0 && $this->init_db) {
			$driver = 'dzf_db_mysql';
			if($this->config['db']['slave']) {
				$driver = 'dzf_db_mysqlslave';
			}
			DB::init($driver, $this->config['db']);
		}
	}

	private function _init_setting() {
		$this->setting = DZF::t('common_syscache')->fetch('stat');
	}
	
	private function _init_user() {
		//var_dump(DZF::ext('ip')->convertip('139.226.75.176'),DZF::ext('ip')->convertip('61.135.172.68'));exit;
		$this->member = DZF::m('member')->fetch_by_mobile($this->mobile);
		if($this->member === false) {
			$this->show_msg(stat_base_msg::MEMBER_ERROR);
		}
	}

	/**
	 * 显示系统中断信息
	 * @param string $code 中断号
	 */
	protected function show_msg($code) {
		stat_base_control::show_msg($code);
	}
	
	public function timezone_set($timeoffset = 8) {
		if(function_exists('date_default_timezone_set')) {
			@date_default_timezone_set('Etc/GMT'.($timeoffset > 0 ? '-' : '+').(abs($timeoffset)));
		}
	}


	/**
	* 设置cookie
	* @param $var - 变量名
	* @param $value - 变量值
	* @param $life - 生命期
	* @param $prefix - 前缀
	*/
	public function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {

		global $_G;

		$config = $_G['config']['cookie'];

		$_G['cookie'][$var] = $value;
		$var = ($prefix ? $config['cookiepre'] : '').$var;
		$_COOKIE[$var] = $value;

		if($value == '' || $life < 0) {
			$value = '';
			$life = -1;
		}


		$life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
		$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];

		$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
		if(PHP_VERSION < '5.2.0') {
			setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
		} else {
			setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
		}
	}

	/**
	* HTML转义字符
	* @param $string - 字符串
	* @param $flags 参见手册 htmlspecialchars
	* @return 返回转义好的字符串
	*/
	public function dhtmlspecialchars($string, $flags = null) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->dhtmlspecialchars($val, $flags);
			}
		} else {
			if($flags === null) {
				$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
				if(strpos($string, '&amp;#') !== false) {
					$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
				}
			} else {
				if(PHP_VERSION < '5.4.0') {
					$string = htmlspecialchars($string, $flags);
				} else {
					if(strtolower(CHARSET) == 'utf-8') {
						$charset = 'UTF-8';
					} else {
						$charset = 'ISO-8859-1';
					}
					$string = htmlspecialchars($string, $flags, $charset);
				}
			}
		}
		return $string;
	}


	public function return_bytes($val) {
	    $val = trim($val);
	    $last = strtolower($val{strlen($val)-1});
	    switch($last) {
	        case 'g': $val *= 1024;
	        case 'm': $val *= 1024;
	        case 'k': $val *= 1024;
	    }
	    return $val;
	}


	/**
	 * 设置全局 $_G 中的变量
	 * @global <array> $_G
	 * @param <string> $key 键
	 * @param <string> $value 值
	 * @return true
	 *
	 * @example
	 * setglobal('test', 1); // $_G['test'] = 1;
	 * setglobal('config/test/abc') = 2; //$_G['config']['test']['abc'] = 2;
	 *
	 */
	public function setglobal($key , $value, $group = null) {
		global $_G;
		$key = explode('/', $group === null ? $key : $group.'/'.$key);
		$p = &$_G;
		foreach ($key as $k) {
			if(!isset($p[$k]) || !is_array($p[$k])) {
				$p[$k] = array();
			}
			$p = &$p[$k];
		}
		$p = $value;
		return true;
	}

	/**
	 * 获取全局变量 $_G 当中的某个数值
	 * @example
	 * $v = getglobal('test'); // $v = $_G['test']
	 * $v = getglobal('test/hello/ok');  // $v = $_G['test']['hello']['ok']
	 *
	 * @global  $_G
	 * @param string $key
	 *
	 * @return type
	 */
	public function getglobal($key, $group = null) {
		global $_G;
		$key = explode('/', $group === null ? $key : $group.'/'.$key);
		$v = &$_G;
		foreach ($key as $k) {
			if (!isset($v[$k])) {
				return null;
			}
			$v = &$v[$k];
		}
		return $v;
	}
	
	public function dstripslashes($string) {
		if(empty($string)) return $string;
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = $this->dstripslashes($val);
			}
		} else {
			$string = stripslashes($string);
		}
		return $string;
	}
	
	public function gmdate($format, $time = 0, $offset = 8) {
		$time = empty($time) ? TIMESTAMP : $time;
		$time = $time + ($offset) * 3600;
		return gmdate($format, $time);
	}
}

class DB extends dzf_base_database{}
class C extends DZF {}
